﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace CapstoneMockup
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel;
            App.ViewModel.WcfConnection.AttemptLoginCompleted += AttemptLoginAsyncCompleted;
        }

        private void ToggleLoginField()
        {
            LoginButton.IsEnabled = password.IsEnabled = Username.IsEnabled = !Username.IsEnabled;
        }

        private void login_Click(object sender, RoutedEventArgs e)
        {
            Button login = sender as Button;
            string username = null, password = null;
            if (login != null)
            {
                username = Username.Text;
                password = this.password.Password;

            }

            loginInfo.Text = "Logging in...";

            ToggleLoginField();

            App.ViewModel.WcfConnection.AttemptLoginAsync(username, password);
        }

        //TODO put this method in a model
        private void AttemptLoginAsyncCompleted(object sender, AttemptLoginCompletedEventArgs args)
        {
            loginInfo.Text = "";

            ToggleLoginField();

            if (args.Result != null)
            {
                App.ViewModel.User = new User(args.Result.Username, UserType.Admin, args.Result.UserId);
                App.ViewModel.GetHours();
                App.ViewModel.GetSaveExpenses();
                NavigationService.Navigate(new Uri("/PivotPage.xaml", UriKind.Relative));
            }
            else
            {
                loginInfo.Text = "Invalid credentials";
            }
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void password_PasswordChanged(object sender, RoutedEventArgs e)
        {

        }
    }
}